package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @author zhenfeng
 * @Date 2021/5/16
 *
 * 秒杀订单消费者
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "MQSeckillOrderCustomer",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
@Slf4j
public class MQSeckillOrderCustomer implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage orderMessage) {
        log.info("进入秒杀下单队列...");
        Long seckillId = orderMessage.getSeckillId();
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long phone = orderMessage.getUserPhone();
        //消息过滤条件
        String tag;
        //创建下单结果封装对象
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setToken(token);
        orderMQResult.setTime(time);
        try {
            //秒杀成功,发送消息给websocket
            String orderNo = orderInfoService.doSeckill(time, seckillId, phone);
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;
            orderMQResult.setOrderNo(orderNo);
            //创建消费封装对象
            Message<OrderMQResult> message = MessageBuilder.withPayload(orderMQResult).build();
            //发送延时消息
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, message, 5000, MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        } catch (Exception e) {
            //秒杀失败,发送消息给websocket和库存回滚消费者
            e.printStackTrace();
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
            //设置秒杀失败状态码和信息
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
        }
        rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC + ":" + tag, orderMQResult);
    }
}
